<?php
namespace services\models;

/**
 * 暂时不使用此文件，在优选后台添加/修改商品后，实时同步商品到喜试优选。
 * 
 * 同步商品、商品详细信息、商品扩展信息、商品价格、商品库存、SKU、SKU详细信息、SKU规格信息、SKU库存到优选数据库。
 *
 * @author huipeng.teng@liketry.com
 */
class SyncGoods extends \common\models\SyncGoods {
    public static function getDb() {
        return \Yii::$app->db;
    }

    /**
     * 同步商品信息到优选数据库
     * 5分钟执行一次
     * 一次同步100个商品
     */
    public static function syncLiketryToBestry() {
        $sql = 'select sync_goods_id,goods_id from ' . self::tableName() . ' where is_success = 0 order by sync_goods_id limit 100';
        $sync_goodsrows = self::getDb()->createCommand($sql)->queryAll();
        if(empty($sync_goodsrows)) {
            return false;
        }

        foreach($sync_goodsrows as $row) {
            if($row['sync_type'] == 1) {
                self::addToBestry($row['sync_goods_id'], $row['goods_id']);// 添加
            } elseif($row['sync_type'] == 2) {
                // 修改
            }
        }
    }

    /**
     * 添加有试吗商品，同时添加商品到喜试优选。
     */
    public static function addToBestry($sync_goods_id, $goods_id) {
        // 同步商品基本信息到tmall1.goods_table表
        $insert_id = self::syncGoods($goods_id);

        if($insert_id > 0) {
            // 同步商品扩展信息到tmall1.goods_table_ext表
            self::syncGoodsExt($goods_id);

            // 同步SKU信息到tmall1.product表
            self::syncProduct($goods_id);

            // 同步SKU规格信息到tmall1.product_spec表
            self::syncProductSpec($goods_id);

            // 更新流水记录状态为处理成功
            self::updateStatus($sync_goods_id);

            // 同步商品信息到WMS
            self::getDb()->createCommand("call tmall1.p_goods_table_update('{$goods_id}',1,'sys',@i,@s)")->execute();
            self::getDb()->createCommand('set names utf8')->execute();
        }
    }

    /**
     * 添加待同步商品到sync_goods表
     * @param int $goods_id 商品ID
     * @return int
     */
    public static function add($goods_id) {
        $dataArray = [];
        $dataArray['goods_id'] = $goods_id;
        $dataArray['create_time'] = date('Y-m-d H:i:s');
        $dataArray['sync_type'] = 1;
        return self::getDb()->createCommand()
                ->insert(self::tableName(), $dataArray)
                ->execute();
    }

    /**
     * 同步商品基本信息
     * @param int $goods_id 商品ID
     * @return bool true | false
     */
    private static function syncGoods($goods_id) {
        // 获取有试吗商品的基本信息
        $goods_row = Goods::findByGoodsIdFromDb($goods_id);

        // 获取有试吗商品的详细信息
        $goods_detail_row = GoodsDetail::findByGoodsIdFromDb($goods_id);

        if(empty($goods_row) || empty($goods_detail_row)) {
            return false;
        }

        // 获取有试吗商品的试用价格和购买价格
        $goods_price_row = GoodsPrice::findByGoodsId($goods_id);

        $dataArray = [];
        $dataArray['uid'] = $goods_row['goods_id'];
        $dataArray['upv'] = $goods_row['status'];
        $dataArray['cate1'] = $goods_row['category_1'];
        $dataArray['category_id'] = $goods_row['category_3'];
        $dataArray['brand_id'] = $goods_row['brand_id'];
        $dataArray['sale_price'] = $goods_price_row['sale_price_rmb'];
        $dataArray['sale_price_jfs'] = $goods_price_row['sale_price_score'];
        $dataArray['buy_price'] = $goods_price_row['try_price_rmb'];
        $dataArray['jfs'] = $goods_price_row['try_price_score'];
        $dataArray['goods_status'] = 1;
        $dataArray['goods_type_id'] = $goods_detail_row['goods_type_id'];
        $dataArray['goods_code'] = $goods_detail_row['goods_code'];
        $dataArray['goods_name'] = $goods_detail_row['goods_name'];
        $dataArray['cost_price'] = $goods_detail_row['cost_price'];
        $dataArray['stock_price'] = $goods_detail_row['stock_price'];
        $dataArray['market_price'] = $goods_detail_row['market_price'];
        $dataArray['goods_kg'] = $goods_detail_row['goods_kg'];
        $dataArray['goods_supply_id'] = $goods_detail_row['goods_supply_id'];
        $dataArray['register_date'] = $goods_detail_row['register_date'];
        $dataArray['update_date'] = $goods_detail_row['update_date'];
        $dataArray['produce_date'] = $goods_detail_row['produce_date'];
        $dataArray['period_day'] = $goods_detail_row['period_day'];
        $dataArray['q_index'] = $goods_detail_row['q_index'];
        $dataArray['storageno'] = $goods_detail_row['storageno'];
        $dataArray['taxrate'] = $goods_detail_row['taxrate'];
        $dataArray['dealkind'] = $goods_detail_row['dealkind'];
        $dataArray['deductrate'] = $goods_detail_row['deductrate'];
        $dataArray['barcode'] = $goods_detail_row['barcode'];
        $dataArray['stockunit'] = $goods_detail_row['stockunit'];
        $dataArray['orderunit'] = $goods_detail_row['orderunit'];
        $dataArray['pcsqty'] = $goods_detail_row['pcsqty'];
        $dataArray['ordqtypit'] = $goods_detail_row['ordqtypit'];
        $dataArray['minstockqty'] = $goods_detail_row['minstockqty'];
        $dataArray['maxstockqty'] = $goods_detail_row['maxstockqty'];
        $dataArray['goods_kind'] = $goods_detail_row['goods_kind'];
        $dataArray['goods_stock_total'] = $goods_detail_row['goods_stock_total'];
        $dataArray['qr_code_pic'] = $goods_detail_row['qr_code_pic'];

        // 插入数据到优选的商品表
        self::getDb()->createCommand()->insert('tmall1.goods_table', $dataArray)->execute();
        $insert_id = self::getDb()->getLastInsertID();

        unset($goods_row, $goods_detail_row, $goods_price_row);

        return $insert_id;
    }

    /**
     * 同步商品扩展信息
     * @param int $goods_id 商品ID
     */
    private static function syncGoodsExt($goods_id) {
        // 获取有试吗商品的扩展信息
        $goods_ext_row = GoodsExt::findByGoodsId($goods_id, 'goods_id,goods_desc');
        if(empty($goods_ext_row)) {
            return false;
        }

        $dataArray = [];
        $dataArray['goods_id'] = $goods_ext_row['goods_id'];
        $dataArray['goods_desc'] = $goods_ext_row['goods_desc'];

        // 插入数据到到优选的商品扩展表
        self::getDb()->createCommand()->insert('tmall1.goods_ext_table', $dataArray)->execute();
        $insert_id = self::getDb()->getLastInsertID();

        return $insert_id;
    }

    /**
     * 同步商品的所有SKU信息
     * @param int $goods_id 商品ID
     */
    private static function syncProduct($goods_id) {
        // 获取有试吗商品的所有SKU信息
        $product_rows = Product::findByGoodsIdFromDb($goods_id);

        foreach($product_rows as $row) {
            // 获取有试吗SKU的详细信息
            $product_detail_row = ProductDetail::findByProductIdFromDb($row['product_id']);

            $dataArray = [];
            $dataArray['uid'] = $row['product_id'];
            $dataArray['goods_id'] = $row['goods_id'];
            if($row['type'] == 1) {
                $dataArray['buy_price'] = $row['sale_price'];// 试用:RMB
                $dataArray['jfs'] = $row['try_price'];// 试用:试豆
            } elseif($row['type'] == 2) {
                $dataArray['sale_price'] = $row['sale_price'];// 购买:RMB
                $dataArray['sale_price_jfs'] = $row['try_price'];// 购买:试豆
            }
            $dataArray['upv'] = $row['sale_status'];
            $dataArray['goods_code'] = $product_detail_row['goods_code'];
            $dataArray['spec_desc'] = $product_detail_row['spec_desc'];
            $dataArray['cost_price'] = $product_detail_row['cost_price'];
            $dataArray['stock_price'] = $product_detail_row['stock_price'];
            $dataArray['barcode'] = $product_detail_row['barcode'];
            $dataArray['source'] = 3;
            $dataArray['type'] = $row['type'];

            // 插入数据到优选的SKU表
            self::getDb()->createCommand()->insert('tmall1.product', $dataArray)->execute();
        }

        unset($product_rows);
    }

    /**
     * 同步商品的所有SKU规格信息
     * @param int $goods_id 商品ID
     */
    private static function syncProductSpec($goods_id) {
        // 获取有试吗商品的SKU规格信息
        $product_spec_rows = ProductSpec::findByGoodsIdFromDb($goods_id);
        if(empty($product_spec_rows)) {
            return false;
        }

        foreach($product_spec_rows as $row) {
            $dataArray = [];
            $dataArray['p_spec_id'] = $row['product_spec_id'];
            $dataArray['product_id'] = $row['product_id'];
            $dataArray['goods_id'] = $row['goods_id'];
            $dataArray['spec_id'] = $row['spec_id'];
            $dataArray['spec_value_id'] = $row['spec_value_id'];
            $dataArray['type_id'] = $row['type_id'];

            // 插入数据到优选的SKU规格信息表
            self::getDb()->createCommand()->insert('tmall1.product_spec', $dataArray)->execute();
        }

        unset($product_spec_rows);
    }

    /**
     * 更新流水记录状态为同步成功
     * @param int $sync_goods_id 流水记录ID
     * @return int
     */
    private static function updateStatus($sync_goods_id) {
        $dataArray = ['is_success' => 1, 'update_time' => date('Y-m-d H:i:s')];
        return self::getDb()->createCommand()
                ->update(self::tableName(), $dataArray, 'sync_goods_id = ' . $sync_goods_id)
                ->execute();
    }
}
